// 登录的本质 使用明文的用户名密码  换取一个暗文的用户名信息的token
//  zhangsan001  123456   =》 token : xxxxzhangsan001yyyy
//  xxxxzhangsan001yyyy   =》 token verify

import { IMiddleware, Middleware } from '@midwayjs/core';
import { Context, NextFunction } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { Admin, Token } from '../entity/adminUser.entity';
import { requestBody } from '../interface/layout';
import { formatDate, generateUniqueStatusCode } from '../commen/tool';
import { LeaveMessage } from '../entity/leaveMessage.entity';

/*
本拦截器 作用于 尽可能多的controller ，需求访问者 必须header携带
authorization: xxxx=zhangsan001=yyyy 用于表明身份
如果没有携带，则不允许访问，如果携带的格式不正确，也不允许访问
*/
@Middleware()
export class AuthInterceptorMiddleware
  implements IMiddleware<Context, NextFunction>
{
  @InjectEntityModel(Token)
  repoToken: Repository<Token>;
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      if (!ctx.request.headers.authorization) {
        return <requestBody>{
          code: -2,
          msg: '无用户信息请登录',
          data: null,
        };
      }
      const tk = await this.repoToken.findOne({
        where: {
          token: ctx.request.headers.authorization,
        },
      });
      if (!tk) {
        return <requestBody>{
          code: -2,
          msg: '无用户信息请登录',
          data: null,
        };
      }
      const result = await next();
      return result;
    };
  }
}
// 模拟登录接口
@Middleware()
export class LoginMiddleware implements IMiddleware<Context, NextFunction> {
  @InjectEntityModel(Token)
  repoToken: Repository<Token>;
  @InjectEntityModel(Admin)
  repoAdmin: Repository<Admin>;
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      if (ctx.path === '/login') {
        const r: any = ctx.request.body;
        const username = r.adminId;
        const password1 = r.password;
        const admin = await this.repoAdmin.findOneBy({ adminId: username });
        if (!admin) {
          return <requestBody>{
            code: -2,
            msg: '用户不存在',
            data: null,
          };
        }

        const password2 = admin.password;
        if (password1 !== password2) {
          return <requestBody>{
            code: -2,
            msg: '密码不正确',
            data: null,
          };
        }
        const tk = new Token();
        tk.token = generateUniqueStatusCode(16);
        const resTk = await this.repoToken.save(tk);
        setTimeout(() => {
          this.repoToken.delete(tk);
        }, 1000 * 60 * 60);
        delete admin.password;
        return <requestBody>{
          code: 0,
          msg: '登陆成功',
          data: {
            token: resTk.token,
            adminInfo: admin,
          },
        };
      } else {
        const result = await next();
        return result;
      }
    };
  }
}
// 方便开发过程中swagger可以不登录就测试 模拟当前登录人叫swagger
@Middleware()
export class LeaveMsgMiddleware implements IMiddleware<Context, NextFunction> {
  @InjectEntityModel(LeaveMessage)
  repoLeaveMessage: Repository<LeaveMessage>;
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      if (ctx.path === '/lmsg') {
        const leaveMessage: any = ctx.request.body;
        leaveMessage.msgID = String(Date.now());
        // if (typeof transport.transportId !== 'string')
        const time = formatDate(new Date());
        leaveMessage.createDate = time;
        leaveMessage.isRead = false;
        const Msg = await this.repoLeaveMessage.save(leaveMessage);
        return <requestBody>{
          code: 0,
          msg: '留言成功',
          data: Msg,
        };
      } else {
        const result = await next();
        return result;
      }
    };
  }
}
@Middleware()
export class SwaggerMiddleware implements IMiddleware<Context, NextFunction> {
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      if (!ctx.headers.authorization) {
        ctx.headers.authorization = 'm3zb6116B8kYnTcB';
      }
      const result = await next();
      return result;
    };
  }
}
